package top.kpromise.fastdev.goods.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import top.kpromise.fastdev.goods.model.request.KongUserInfo;
import top.kpromise.fastdev.goods.wrapper.HeaderMapRequestWrapper;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class LoginFilter implements Filter {

    private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    @Override
    public void init(FilterConfig filterConfig) {
        System.out.println("LoginFilter init !");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        System.out.println("LoginFilter start");
        if (!(request instanceof HttpServletRequest)) {
            return;
        }
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String userId = httpServletRequest.getHeader("x-authenticated-userid");
        String anonymous = httpServletRequest.getHeader("X-Anonymous-Consumer");

        logger.info("userId " + userId);
        logger.info("anonymous " + anonymous);

        KongUserInfo kongUserInfo = null;
        if (userId != null) {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                kongUserInfo = objectMapper.readValue(userId, KongUserInfo.class);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }

        HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(httpServletRequest);
        if (kongUserInfo != null) {
            requestWrapper.addHeader("userId", kongUserInfo.getUserId());
            requestWrapper.addHeader("originId", userId);
        }
        requestWrapper.addHeader("hasLogin", String.valueOf((anonymous == null)));
        chain.doFilter(requestWrapper, response);
    }

    @Override
    public void destroy() {
        System.out.println("LoginFilter destroy!");
    }
}
